package com.zlzsy.app.base.ui

import android.os.Bundle
import android.support.annotation.StringRes
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.MenuItem
import com.afollestad.materialdialogs.MaterialDialog
import com.zlzsy.app.base.R
import com.zlzsy.app.base.ui.interfaces.IActivity


/**
 * Created by niantuo on 2017/11/6.
 * 所有 activity的封装基类
 */
open class BaseActivity : AppCompatActivity(), IActivity {

    private val TAG: String = BaseActivity::class.java.simpleName
    private var loadingDialog: MaterialDialog? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initData(savedInstanceState)
    }

    protected open fun initView() {}

    protected open fun initData(savedInstanceState: Bundle?) {}


    /**
     * 显示加载框
     */
    override fun showLoadingDialog() {
        showLoadingDialog(R.string.load_title)
    }

    /**
     * 显示加载对话框，不可自动取消
     */
    override fun showLoadingDialog(@StringRes titleRes: Int) {
        showLoadingDialog(getString(titleRes))
    }

    override fun showLoadingDialog(message: String) {
        if (loadingDialog == null) {
            loadingDialog = MaterialDialog.Builder(this)
                    .title(message)
                    .progress(true, 0)
                    .autoDismiss(false)
                    .cancelable(true)
                    .show()
        } else {
            loadingDialog?.setTitle(message)
        }
    }

    override fun showAlert(msg: String) {
        MaterialDialog.Builder(this)
                .title("提示")
                .content(msg)
                .positiveText("确定")
                .show()
    }

    /**
     * 隐藏加载框
     */
    override fun hideLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog?.dismiss()
            loadingDialog = null
        }
        Log.i(TAG, "hideLoadingDialog : $loadingDialog")
    }

    override fun onDestroy() {
        super.onDestroy()
        loadingDialog?.dismiss()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

}